<?php

namespace App\Http\Controllers;

use App\Models\Enterprise;
use App\Models\MdClient;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SyncController extends Controller
{
    /**
     * 同步
     * create_at: 2025-01-11 16:56:34
     * update_at: 2025-01-11 16:56:34
     */
    public function sync()
    {
        set_time_limit(0);

        $now = date('Y-m-d H:i:s');
        $redis = app("redis.connection");
        $key = 'num';

        // 分批处理
        $mdClients = MdClient::where(["mark" => 2])->chunk(200, function ($clients) use ($redis, $key, $now) {
            try {
                $clients->each(function ($mdClient) use ($redis, $key, $now) {
//                dd($mdClient);
                    $data = [
                        'ent_guid' => $this->genGuid(),
                        'ent_name' => $mdClient->client_name,
                        'add_time' => $now,
                        'edit_time' => $now,
                        'currency_type' => '万元人民币',
                        'ent_addr' => $mdClient->address ?: '',
                        'linkman' => $mdClient->contact1 ?: '',
                        'linkman_mobile' => $mdClient->contact1_tel ?: '',
                        'email' => $mdClient->email ?: '',
                        'ent_jd' => $mdClient->lng ?: 0,
                        'ent_wd' => $mdClient->lat ?: 0,
                        'grade' => 100,
                        'source' => 'erp',
                        'entlabel' => '[{"firstlabelId":1705,"firstlabelName":"类型标签","secondLabelList":[{"secondlabelId":1714,"secondlabelName":"其他"}]}]',
                    ];

                    Enterprise::create($data);

                    $redis->incr($key);
                });
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }
        });
    }

    /**
     * 生成 guid
     * @return string
     * create_at: 2024-12-20 16:15:37
     * update_at: 2024-12-20 16:15:37
     */
    protected function genGuid()
    {
        $guid = $this->create_guid();
        $exist = Enterprise::where(['ent_guid' => $guid])->whereNull("deleted_at")->exists();
        if ($exist) {
            return $this->genGuid();
        } else {
            return $guid;
        }
    }

    /**
     * 生成GUID
     * @return string
     * create_at: 2024-12-20 16:15:45
     * update_at: 2024-12-20 16:15:45
     */
    protected function create_guid()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }

        return strtolower(
            sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535))
        );
    }
}
